package location

import (
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"strings"
)



func GetAllConfigFromFile() map[string]string {
	config := make(map[string]string)

	root := ".\\config\\";
	err := filepath.Walk(root, func(p string, info os.FileInfo, err error) error {
		//fmt.Println(p)
		if (IsDir(p)) {
			return nil
		}
		b,err := ioutil.ReadFile(p)
		if err != nil {
			fmt.Println("ioutil.ReadFile",p,err.Error())
			return err
		}

		key := strings.TrimSuffix(info.Name(),path.Ext(p));
		fmt.Println(key,":",string(b))
		config[key] = string(b)
		return nil
	})
	fmt.Println(err)
	//fmt.Println(Config)
	return config
}

func UpdateConfig(key string,value string) bool {
	name := fmt.Sprintf("./config/%s.txt",key)

	//if Config[key] == value {
	//	fmt.Println(key,":",value,"一样,不用更新")
	//	return true;
	//}
	return WriteConfigFile(name,value)
}
//写入配置文件
func WriteConfigFile(name string,value string) bool {
	file,err := os.Create(name)
	if err != nil {
		fmt.Println("os.Create,更新配置失败",name,value,err.Error())
		return false;
	}
	_,err = file.Write([]byte(value))
	if err != nil {
		fmt.Println("file.Write,更新配置失败",name,value,err.Error())
		return false;
	}
	//Config[key] = value
	return true
}

var pidFile = "./main.pid"

func UpdatePid(pid int) bool {
	pid1 := strconv.Itoa(pid)
	return WriteConfigFile(pidFile,pid1)
}

func GetPidFromFile() int {
	b,err := ioutil.ReadFile(pidFile)
	if err != nil {
		return 0
	}
	pid,err := strconv.Atoi(string(b))
	if err != nil {
		return 0
	}
	return pid
}